﻿/*
 * 文件名称：
 * 程序员：wangyun
 * 创建时间：2008/07/07
 * 
 * 功能说明：ezEIP 安装页面
 * 
 * 修改人员：
 * 
 * 修改日期：
 * 
 * 修改记录：
 */

using System;
using System.Data;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Xml;
using Whir.Common;
using System.Data.SqlClient;
using Whir.Common.WebHelper;
using System.IO;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Text;

public partial class Install_Next : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.SetActivePanel(WizardPanel.Welcome, this.Welcome);
        }
    }

    #region
    /// <summary>
    /// 获取产品名称
    /// </summary>
    protected string GetProductName()
    {
        return Settings.GetString("ProductName");
    }

    /// <summary>
    /// 获取连接服务器字符串
    /// </summary>
    protected string GetConnectionString()
    {
        return string.Format("Data Source={0};User ID={1};Password={2};Trusted_Connection={3}",
            new object[] { 
                this.txtServerName.Text, 
                this.txtDbUserName.Text, 
                this.txtDbPassword.Text, 
                (this.rblConnectToDb.SelectedIndex == 0) ? "true" : "false" });
    }

    /// <summary>
    /// 获取连接数据库字符串
    /// </summary>
    protected string GetDatabaseConnectionString()
    {
        string dbName = rblSelectDb.SelectedIndex == 0 ? this.txtDbName.Text : ddlDataBaseList.SelectedValue;   //数据库名
        return string.Format("{0};Initial Catalog={1}", this.GetConnectionString(), dbName);
    }

    /// <summary>
    /// 验证服务器连接
    /// </summary>    
    protected bool ValidateConnection()
    {
        try
        {
            using (SqlConnection connection = new SqlConnection(this.GetConnectionString()))
            {
                connection.Open();
                connection.Close();
            }
            return true;
        }
        catch (SqlException ex)
        {
            this.WriteInfoMessage(ex.Message);
            return false;
        }
    }

    /// <summary>
    /// 验证数据库连接
    /// </summary>    
    protected bool ValidateConnectionDb()
    {
        try
        {
            using (SqlConnection connection = new SqlConnection(this.GetDatabaseConnectionString()))
            {
                connection.Open();
                connection.Close();
            }
            return true;
        }
        catch (SqlException ex)
        {
            this.WriteInfoMessage(ex.Message);
            return false;
        }
    }
    #endregion

    #region 安装数据库
    /// <summary>
    /// 安装数据库
    /// </summary>    
    private bool InstallDatabase()
    {
        bool flag = false;
        if (UpdateConfig())
        {
            try
            {
                string adminName = this.txtDbUserName.Text; //数据库登录名
                string adminPwd = this.txtDbPassword.Text;  //数据库登录密码
                string server = this.txtServerName.Text;    //服务器名称
                string dbName = rblSelectDb.SelectedIndex == 0 ? this.txtDbName.Text : ddlDataBaseList.SelectedValue;   //数据库名
                string infile = System.Web.HttpContext.Current.Server.MapPath("~/Install/sqlscript/ezeip.sql"); //

                // 执行SQL 语句
                Process sqlprocess = new Process();
                sqlprocess.StartInfo.FileName = "osql.exe";
                sqlprocess.StartInfo.Arguments = String.Format("-U {0} -P {1} -S {2} -d {3} -i {4}", adminName, adminPwd, @server, dbName, @infile); //U为用户名,P为密码,S为目标服务器的ip,infile为数据库脚本所在的路径 
                sqlprocess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                sqlprocess.Start();
                sqlprocess.WaitForExit(); //等待程序执行.Sql脚本
                sqlprocess.Close();

                flag = true;
            }
            catch (Exception ex)
            {
                flag = false;
                this.WriteInfoMessage(ex.Message);
            }
        }
        return flag;
    }
    #endregion

    #region 更新Web.Config 配置文件
    /// <summary>
    /// 更新Web.Config 配置文件
    /// </summary>
    private bool UpdateConfig()
    {
        string m_ApplicationPath = Request.ApplicationPath;
        if (m_ApplicationPath == "")
            m_ApplicationPath = "/";
        if (!m_ApplicationPath.EndsWith("/"))
            m_ApplicationPath += "/";

        bool flag = false;
        try
        {
            XmlDocument document = new XmlDocument();
            document.PreserveWhitespace = true;
            string filename = HttpContext.Current.Server.MapPath("~/Web.Config");
            document.Load(filename);
            bool flag2 = false;
            foreach (XmlNode node2 in document.SelectSingleNode("configuration/connectionStrings"))
            {
                if (node2.Name == "add")
                {
                    XmlAttribute attribute = node2.Attributes["name"];
                    if (attribute != null)
                    {
                        if (attribute.Value == "SQLConnString")
                        {
                            XmlAttribute attribute2 = node2.Attributes["connectionString"];
                            if (attribute2 != null)
                            {
                                attribute2.Value = this.GetDatabaseConnectionString();
                                flag2 = true;
                            }
                        }
                    }
                }
            }
            foreach (XmlNode node2 in document.SelectSingleNode("configuration/appSettings"))
            {
                if (node2.Name == "add")
                {
                    XmlAttribute attribute = node2.Attributes["key"];
                    if (attribute != null)
                    {
                        if (attribute.Value == "PicServer" || attribute.Value == "ItemPicPath"
                            || attribute.Value == "AdminPath" || attribute.Value == "SystemPath"
                            || attribute.Value == "XmlPath" || attribute.Value == "FCKeditor:UserFilesPath")
                        {
                            XmlAttribute attribute2 = node2.Attributes["value"];
                            if (attribute2 != null)
                            {
                                attribute2.Value = m_ApplicationPath + attribute2.Value.Substring(9);
                                flag2 = true;
                            }
                        }
                    }
                }
            }
            if (flag2)
            {
                XmlTextWriter w = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
                w.Formatting = Formatting.Indented;
                document.Save(w);
                w.Flush();
                w.Close();
            }
            flag = true;
        }
        catch (Exception ex)
        {
            this.WriteInfoMessage(ex.Message);
            flag = false;
        }
        return flag;
    }
    #endregion

    #region 输出提示信息
    /// <summary>
    /// 输出提示信息
    /// </summary>
    protected void WriteInfoMessage(string message)
    {
        ltMessage.Visible = true;
        ltMessage.Text = message;
    }
    #endregion

    #region 绑定数据库列表
    /// <summary>
    /// 绑定数据库列表
    /// </summary>
    protected void BindDataBaseList()
    {
        SqlConnection connection = new SqlConnection(this.GetConnectionString());
        SqlCommand command = new SqlCommand("select name from master..sysdatabases order by name asc", connection);
        connection.Open();
        connection.ChangeDatabase("master");
        SqlDataReader reader = command.ExecuteReader();
        this.ddlDataBaseList.Items.Clear();
        while (reader.Read())
        {
            string item = reader["name"] as string;
            if ((((item != null) && (item != "master")) && ((item != "msdb") && (item != "tempdb"))) && (item != "model"))
            {
                this.ddlDataBaseList.Items.Add(item);
            }
        }
        connection.Close();
    }
    #endregion

    #region 上一步操作
    protected void Previous_Click(object sender, ImageClickEventArgs e)
    {
        switch (this.CurrentWizardPanel)
        {
            case WizardPanel.License:
                this.SetActivePanel(WizardPanel.Welcome, this.Welcome);
                break;

            case WizardPanel.ConnectToDb:
                this.SetActivePanel(WizardPanel.License, this.License);
                break;

            case WizardPanel.SelectDb:
                this.SetActivePanel(WizardPanel.ConnectToDb, this.ConnectToDb);
                break;

            case WizardPanel.AdminOptions:
                this.SetActivePanel(WizardPanel.SelectDb, this.SelectDb);
                break;

            case WizardPanel.Done:
                this.SetActivePanel(WizardPanel.SelectDb, this.SelectDb);
                break;

            case WizardPanel.SchemaExists:
                this.SetActivePanel(WizardPanel.SelectDb, this.SelectDb);
                break;
        }
    }
    #endregion

    #region 下一步操作
    protected void Next_Click(object sender, ImageClickEventArgs e)
    {
        switch (this.CurrentWizardPanel)
        {
            case WizardPanel.Welcome:
                this.SetActivePanel(WizardPanel.License, this.License);
                break;

            case WizardPanel.License:
                //必须同意许可
                if (this.chkIAgree.Checked)
                    this.SetActivePanel(WizardPanel.ConnectToDb, this.ConnectToDb);
                else
                    this.WriteInfoMessage("请同意" + GetProductName() + "许可协议");
                break;

            case WizardPanel.ConnectToDb:
                //如果是SQL Server 身份验证需输入账号和密码
                if (rblConnectToDb.SelectedIndex == 1)
                {
                    if (txtDbUserName.Text.Trim() == "" || txtDbPassword.Text.Trim() == "")
                    {
                        this.WriteInfoMessage("请输入SQL Server 身份验证的账号和密码！");
                        break;
                    }
                }

                //验证连接服务器是否成功
                if (this.ValidateConnection())
                {
                    //绑定服务器上的数据库列表
                    BindDataBaseList();
                    this.SetActivePanel(WizardPanel.SelectDb, this.SelectDb);
                }
                else
                    this.WriteInfoMessage("服务器连接失败！");
                break;

            case WizardPanel.SelectDb:
                if (this.rblSelectDb.SelectedIndex == 0)
                {
                    string newDbName = txtDbName.Text.Trim();
                    if (string.IsNullOrEmpty(newDbName))
                    {
                        this.WriteInfoMessage("请输入新数据库名称！");
                        break;
                    }
                    else
                    {
                        ExecuteSql("master", "USE MASTER IF EXISTS (SELECT NAME FROM SYSDATABASES WHERE NAME='" + newDbName + "') DROP DATABASE " + newDbName);
                        ExecuteSql("master", "CREATE DATABASE " + newDbName);
                    }
                }

                //验证连接数据库是否成功
                if (this.ValidateConnectionDb())
                {
                    this.SetActivePanel(WizardPanel.AdminOptions, this.AdminOptions);
                }
                break;

            case WizardPanel.AdminOptions:
                hdPassword.Value = this.txtAdminPwdRe.Text;
                this.SetActivePanel(WizardPanel.Done, this.Done);
                break;
            case WizardPanel.Done:
                break;
        }
    }
    #endregion

    #region 执行sql语句
    /// <summary>
    /// 执行sql语句
    /// </summary>
    /// <param name="DataBaseName">数据库名称</param>
    /// <param name="sqlstring">sql 语句</param>
    private void ExecuteSql(string DataBaseName, string sqlstring)
    {
        using (SqlConnection conn = new SqlConnection(this.GetConnectionString()))
        {
            SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sqlstring, conn);
            conn.Open();
            cmd.Connection.ChangeDatabase(DataBaseName);
            cmd.ExecuteNonQuery();
            conn.Close();
        }
    }
    #endregion

    #region 设置面板显示/隐藏
    /// <summary>
    /// 设置面板显示/隐藏
    /// </summary>
    private void SetActivePanel(WizardPanel panel, Control controlToShow)
    {
        ltMessage.Visible = false;
        Panel panel2 = this.FindControl(this.CurrentWizardPanel.ToString()) as Panel;
        if (panel2 != null)
        {
            panel2.Visible = false;
        }
        switch (panel)
        {
            case WizardPanel.Done:
                this.btnSubmit.Visible = true;
                this.Next.Visible = false;
                this.Previous.Visible = false;
                break;

            case WizardPanel.SchemaExists:
                this.Previous.Enabled = true;
                this.Next.Enabled = false;
                break;

            case WizardPanel.Errors:
                this.Previous.Enabled = false;
                this.Next.Enabled = false;
                break;

            case WizardPanel.Welcome:
                this.Previous.Enabled = false;
                this.License.Visible = false;
                break;
            default:
                this.Previous.Enabled = true;
                this.Next.Enabled = true;
                break;
        }
        controlToShow.Visible = true;
        this.CurrentWizardPanel = panel;
    }
    #endregion

    #region 当前面板
    /// <summary>
    /// 当前面板
    /// </summary>
    public WizardPanel CurrentWizardPanel
    {
        get
        {
            if (this.ViewState["WizardPanel"] != null)
            {
                return (WizardPanel)this.ViewState["WizardPanel"];
            }
            return WizardPanel.Welcome;
        }
        set
        {
            this.ViewState["WizardPanel"] = value;
        }
    }
    #endregion

    protected void rblConnectToDb_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.rblConnectToDb.SelectedIndex == 0)
            sqlInfo.Visible = false;
        else
            sqlInfo.Visible = true;
    }

    protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
    {
        bool flag = false;

        //计算程序生成所使用的时间
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();

        //安装数据库
        flag = InstallDatabase();

        if (flag)
        {
            try
            {
                lbDoneSuccess.Text = "正在安装，请稍候...";
                btnSubmit.Visible = false;
                //添加初始记录
                string dbName = rblSelectDb.SelectedIndex == 0 ? this.txtDbName.Text : ddlDataBaseList.SelectedValue;   //数据库名

                string insertSql1 = "INSERT [Whir_AdminRole] ([roleName],[roleDesc],[roleValue],[columnIDs],[createDate],[createUserID],[updateDate],[updateUserID]) VALUES ('管理员','管理员','0000011100000000',',0,','" + DateTime.Now + "',0,'" + DateTime.Now + "',0)";
                string insertSql2 = string.Format("INSERT [Whir_AdminInfo] ([adminName],[adminPassword],[adminTrueName],[typeID],[roleIDs],[roleValue],[createDate],[createUserID]) VALUES ('{0}','{1}','{2}',{3},'{4}','{5}','{6}',{7})", txtAdminName.Text, Whir.Common.WebHelper.StringHelper.GetSHA1Str(hdPassword.Value), "系统管理员", 1, "", "", DateTime.Now, 0);

                ExecuteSql(dbName, insertSql1);
                ExecuteSql(dbName, insertSql2);

                //获取程序生成所花费时间
                TimeSpan ts = stopWatch.Elapsed;
                string time = String.Format("{0:00}.{1:00}秒", ts.Seconds, ts.Milliseconds / 10);
                stopWatch.Stop();

                //完成安装
                lbDoneSuccess.Text = " 恭喜，您已经完成了 " + GetProductName() + " 安装，并已正常运行。<br />程序生成时间: " + time;
                btnSubmit.ImageUrl = "images/btn_stop.jpg";
                btnSubmit.Enabled = false;
                DoneSuccess.Visible = true;
            }
            catch
            {
                WriteInfoMessage("数据库数据导入失败！");
            }
        }
        else
        {
            WriteInfoMessage("数据库安装失败！");
        }
    }

    protected void rblSelectDb_SelectedIndexChanged(object sender, EventArgs e)
    {
        //新建数据库或已有数据库
        if (this.rblSelectDb.SelectedIndex == 0)
        {
            dbNew.Visible = true;
            dbOld.Visible = false;
            ltMessage.Visible = false;
        }
        else
        {
            dbOld.Visible = true;
            dbNew.Visible = false;
            ltMessage.Visible = false;
        }
    }
}